
package mars.game.core;

import android.content.Context;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MarsGameView extends SurfaceView implements
		SurfaceHolder.Callback, Runnable
{

	public static final int FPS = 100;
	
	public GameScreen currGameScreen;

	// 控制循环
	boolean mbLoop = false;

	// 定义SurfaceHolder对象
	SurfaceHolder mSurfaceHolder = null;

	

	public MarsGameView(Context context)
	{

		super(context);

		// 实例化SurfaceHolder
		mSurfaceHolder = this.getHolder();

		// 添加回调
		mSurfaceHolder.addCallback(this);
		this.setFocusable(true);

		mbLoop = true;
	}

	// 在surface的大小发生改变时激发
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height)
	{

	}

	// 在surface创建时激发
	public void surfaceCreated(SurfaceHolder holder)
	{

		// 开启绘图线程
		new Thread(this).start();
	}

	// 在surface销毁时激发
	public void surfaceDestroyed(SurfaceHolder holder)
	{

		// 停止循环
		mbLoop = false;
	}

	// 绘图循环
	public void run()
	{

		while (mbLoop)
		{
			try
			{
				Thread.sleep(FPS);
			} catch (Exception e)
			{

			}
			synchronized (mSurfaceHolder)
			{
				if(currGameScreen != null)
				{
					// 锁定画布，得到canvas
					Canvas canvas = mSurfaceHolder.lockCanvas();

					if (mSurfaceHolder == null || canvas == null)
					{
						return;
					}
					currGameScreen.draw(canvas);
					
					// 绘制后解锁，绘制后必须解锁才能显示
					mSurfaceHolder.unlockCanvasAndPost(canvas);
				}
				
			}

		}
	}

}